﻿using MvcWechat.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MvcWechat.Areas.Manager.Controllers
{
    public class MenuController : Controller
    {
        //
        // GET: /Manager/Memu/
        public static string acctoken = WeixinConfigs.WxokenHelper.GetToken();
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult CreateMenu(JObject obj)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}", acctoken);
            var data = JsonConvert.SerializeObject(obj);
            var json = DynamicJson.Parse(Util.HttpRequestPost(url, data).Result);
            if (json.errcode != 0)
                Logger.Debug(this.GetType(), json);
            return Json(json.ToString());
        }

        public JsonResult GetConditionalMenu()
        {
            //return Json("{\"button\":[{\"name\":\"扫码\",\"sub_button\":[{\"type\":\"scancode_waitmsg\",\"name\":\"扫码带提示\",\"key\":\"rselfmenu_0_0\",\"sub_button\":[]},{\"type\":\"scancode_push\",\"name\":\"扫码推事件\",\"key\":\"rselfmenu_0_1\",\"sub_button\":[]}]},{\"name\":\"发图\",\"sub_button\":[{\"type\":\"pic_sysphoto\",\"name\":\"系统拍照发图\",\"key\":\"rselfmenu_1_0\",\"sub_button\":[]},{\"type\":\"pic_photo_or_album\",\"name\":\"拍照或者相册发图\",\"key\":\"rselfmenu_1_1\",\"sub_button\":[]},{\"type\":\"pic_weixin\",\"name\":\"微信相册发图\",\"key\":\"rselfmenu_1_2\",\"sub_button\":[]}]},{\"name\":\"发送位置\",\"type\":\"location_select\",\"key\":\"rselfmenu_2_0\"},{\"type\":\"media_id\",\"name\":\"图片\",\"media_id\":\"MEDIA_ID1\"},{\"type\":\"view\",\"name\":\"消息\",\"url\":\"http://www.soso.com/\"}]}", JsonRequestBehavior.AllowGet);
            return Json(BasicAPI.GetConditionalMenu(acctoken), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 微信短网址转换
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetShortUrl()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            var longUrl=ControllerContext.RequestContext.HttpContext.Request.QueryString["url"];
            if (longUrl == null||longUrl=="")
            {
                return Json(new { msg = "添加 ?url=www.xxx.com" }, JsonRequestBehavior.AllowGet);
            }
            else {
                var urlObj = Util.GetShortUrlByLongUrl(longUrl, acctoken);
                var anonymousResult = new { errcode = 0, errmsg = "", short_url = "" }; //用来接收返回的类
                anonymousResult = JsonConvert.DeserializeAnonymousType(urlObj, anonymousResult);
                return Json(anonymousResult, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
